<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="8">
          <el-table :data="dbTableList" border>
            <el-table-column prop="tableName" :label="$t('表名称')" />
            <el-table-column prop="tableComment" :label="$t('表描述')">
              <template slot-scope="scope">
                {{ $t(scope.row.tableComment) }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <el-row class="dataForm" style="margin-left: 15px;">
            <el-col :span="12">
              <el-form-item :label="$t('数据集名称')" prop="name">
                <el-input v-model="form.name" :placeholder="$t('数据集名称')" show-word-limit maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('唯一编码')" prop="uniqueCode">
                <el-input v-model="form.uniqueCode" :placeholder="$t('唯一编码')" show-word-limit maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('数据包')" prop="dataPackageCode">
                <el-select v-model="form.dataPackageCode">
                  <el-option
                    v-for="item in jmfDataPackageOptions"
                    :key="item.code"
                    :value="item.code"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('是否主数据集')" prop="whetherMainData">
                <el-radio-group v-model="form.whetherMainData">
                  <el-radio
                    v-for="(item) in systemYesNoOptions"
                    :key="item.dictValue"
                    :label="item.dictValue"
                  >{{ item.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col v-if="form.whetherMainData === 'Y'" :span="12">
              <el-form-item :label="$t('主字段')" prop="mainField">
                <el-input v-model="form.mainField" show-word-limit maxlength="25" :placeholder="$t('主字段')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('类型')" prop="type">
                <dict-select
                  v-model="form.type"
                  dictionary="data_set_type"
                  multiple
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('Sql脚本')" prop="sqlScript">
                <textarea ref="sqlScript" v-model="form.sqlScript" class="codesql" style="height:500px;width:600px;" />
              </el-form-item>
            </el-col>
            <div class="area-header mt-15" style="display: flex;width: 100%;align-items: center;">
              <span class="area-header-title" style="flex: 1;">
                {{ $t('字段列表') }}
              </span>
              <el-button
                v-hasPermi="['jmf:dataSet:edit']"
                type="primary"
                size="mini"
                @click="getColumnBySql"
              >{{ $t('刷新') }}</el-button>
            </div>
            <el-table
              v-if="filedShow"
              :data="form.fieldList"
              border
              class="nowrapTable formTable"
            >
              <el-table-column :label="$t('字段名称')" align="center">
                <template slot-scope="scope">
                  {{ scope.row.code }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('字段别名')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('字段别名') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'fieldList.' + scope.$index + '.label'" :rules="fieldListRules.label">
                    <el-input v-model="scope.row.label" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('字段类型')" align="center">
                <template slot="header" slot-scope="{}">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span>{{ $t('字段类型') }}</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="'fieldList.' + scope.$index + '.type'" :rules="fieldListRules.type">
                    <el-select
                      v-model="scope.row.type"
                      clearable
                      :placeholder="$t('请选择')"
                      style="width: 100%"
                      @change="updateFormatValue(scope.row)"
                    >
                      <el-option
                        v-for="field in filedTypeOptions"
                        :key="field.dictValue"
                        :label="$t(field.dictLabel)"
                        :value="field.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('关联数据集')" align="center" prop="">
                <template slot-scope="scope">
                  <el-popover
                    placement="top"
                    :title="$t('关联数据集')"
                    width="200"
                    trigger="click"
                  >
                    <el-row>
                      <el-col :span="24">
                        <p>{{ $t('数据集') }}:</p>
                        <el-select v-model="scope.row.joinDataCode" clearable :placeholder="$t('数据集')" @change="joinDataCodeChange($event, scope.$index)">
                          <el-option
                            v-for="item in joinDataOptions"
                            :key="item.uniqueCode"
                            :value="item.uniqueCode"
                            :label="item.name"
                          />
                        </el-select>
                      </el-col>
                      <el-col :span="24">
                        <p>{{ $t('数据集字段') }}:</p>
                        <el-select v-model="scope.row.joinDataFieldName" clearable :placeholder="$t('关联数据集字段')">
                          <el-option
                            v-for="item in fieldOptions"
                            :key="item.id"
                            :value="item.code"
                            :label="item.label"
                          />
                        </el-select>
                      </el-col>
                    </el-row>
                    <el-button slot="reference" :type="scope.row.joinDataCode && scope.row.joinDataFieldName ? 'success' : 'primary'">{{ scope.row.joinDataId && scope.row.joinDataFieldId ? $t('更改数据集') : $t('关联数据集') }}</el-button>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column :label="$t('格式化')" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="'fieldList.' + scope.$index + '.type'">
                    <el-input v-if="scope.row.type === 'RQ' || scope.row.type === 'JE'" v-model="scope.row.format" />
                    <el-select
                      v-if="scope.row.type === 'ZD'"
                      v-model="scope.row.format"
                      value=""
                      clearable
                      filterable
                      :placeholder="$t('请选择')"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="dict in dictOptions"
                        :key="dict.dictType"
                        :label="$t(dict.dictName)"
                        :value="dict.dictType"
                      >
                        <span style="float: left">{{ dict.dictName }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--<el-table-column :label="$t('打开页面" align="center">-->
              <!--</el-table-column>-->
              <!--<el-table-column :label="$t('页面参数" align="center">-->
              <!--</el-table-column>-->
              <el-table-column :label="$t('是否展示给用户')" align="center" width="100">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isShow"
                    active-value="Y"
                    inactive-value="N"
                  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('是否必选')" align="center" width="100">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.whetherChoose"
                    active-value="Y"
                    inactive-value="N"
                  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('排序')" align="center" width="100">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sort" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('默认宽度')" align="center" width="100">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.width" />
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="jmf:dataSet" />
    </div>
  </div>
</template>

<script>
import { saveJmfDataSet, getJmfDataSet, listJmfDataSet, getByDataSetCode } from '@/api/dev/jmf/jmfDataSet'
    import { listDbTable } from '@/api/tool/gen'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'
    import { getColumnBySql } from '@/api/system/search/searchSqlBase'
    import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
    import { listJmfDataPackage } from '@/api/dev/jmf/jmfDataPackage'

const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
        name: 'CodeMirror',
        data() {
            return {
                // 表单参数
                form: {
                },
                // 字典列表是否显示
                filedShow: true,
                // 遮罩层
                loading: false,
                // 字段类型字典
                filedTypeOptions: [],
              // j魔方数据包
              jmfDataPackageOptions: [],
              // 系统是否字典
              systemYesNoOptions: [],
              // 字典信息
                dictOptions: [],
              fieldOptions: [],
                editor: {},
                // 数据库表集合
                dbTableList: [],
                // 关联数据集数组
                joinDataOptions: [],
                // 关联数据集字段数组
                joinDataFieldOptions: [],
                // 表单校验
                rules: {
                  name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  sqlScript: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  uniqueCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  mainField: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                fieldListRules: {
                  label: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  type: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
                }
            }
        },
        created() {
          this.getDicts('search_field_type').then(response => {
            this.filedTypeOptions = response.data
          })
          /** 查询字典下拉列表 */
          getDictOptionselect().then(response => {
            this.dictOptions = response.data
          })
          this.getDicts('sys_yes_no').then(response => {
            this.systemYesNoOptions = response.data
          })
          listJmfDataPackage().then(res => {
            this.jmfDataPackageOptions = res.rows
          })
        },
        mounted() {
          const mime = 'text/x-mariadb'
          // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
          this.editor = CodeMirror.fromTextArea(this.$refs.sqlScript, {
            mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            // theme: theme,
            autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
            hintOptions: { // 自定义提示选项
              tables: {
                users: ['name', 'score', 'birthDate'],
                countries: ['name', 'population', 'size']
              }
            }
          })
          this.editor.on('cursorActivity', function() {
            if (this !== null) {
              this.editor.showHint()
            }
          })
          listJmfDataSet().then(response => {
            this.joinDataOptions = response.rows
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                    getJmfDataSet(data.id).then(response => {
                        this.form = response.data
                        this.editor.setValue(this.form.sqlScript !== null ? this.form.sqlScript : '')
                    })
                } else {
                    this.reset()
                }
                // 加载数据库表
                this.listDbTable()
            },
            // 表单重置
            reset() {
                this.form = {
                  id: undefined,
                  uniqueCode: undefined,
                  dataPackageCode: undefined,
                  whetherMainData: 'N',
                  mainField: undefined,
                  name: undefined,
                  whetherChoose: 'N',
                  sqlScript: undefined,
                  createBy: undefined,
                  createTime: undefined,
                  updateBy: undefined,
                  updateTime: undefined,
                  fieldList: [],
                  type: []
                }
                this.editor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.form.sqlScript = this.editor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveJmfDataSet(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        }).catch(() => {
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 获取表集合
          listDbTable: function() {
            listDbTable({}).then(res => {
              if (res.code === 200) {
                this.dbTableList = res.rows
              }
            })
          }, getColumnBySql: function() {
            this.form.searchSql = this.editor.getValue()
            if (this.form.searchSql === null || this.form.searchSql === '') {
              this.$message.error('sql脚本不能为空')
            } else {
              getColumnBySql(this.form).then(response => {
                // 保存之前配置的数据
                var fieldTempMap = {}
                for (var j = 0; j < this.form.fieldList.length; j++) {
                  var filed = this.form.fieldList[j]
                  fieldTempMap[filed.code] = filed
                }
                var fieldList = []
                for (var i = 0; i < response.data.length; i++) {
                  var field = {}
                  if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                    field = fieldTempMap[response.data[i]]
                    field.sort = (i + 1) * 10
                  } else {
                    field.code = response.data[i]
                    field.label = response.data[i]
                    field.type = 'WB'
                    field.isShow = 'Y'
                    field.sort = (i + 1) * 10
                    field.width = 200
                  }
                  fieldList.push(field)
                  this.$set(this.form, 'fieldList', fieldList)
                  this.filedShow = false
                  this.filedShow = true
                }
              })
            }
          },
          // 设置格式化字段默认值
          updateFormatValue: function(row) {
            if (row.type === 'JE') {
              row.format = '###,###.####'
            } else if (row.type === 'RQ') {
              row.format = 'yyyy-MM-dd'
            }
          },
          joinDataCodeChange(val, index) {
            this.$set(this.form.fieldList[index], 'joinDataFieldName', undefined)
            getByDataSetCode({ dataSetCode: val, category: 'data_set' }).then(res => {
              this.fieldOptions = res.data
            })
          }
        }

    }
</script>
<style scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
